package com.example.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.base.utils.FfmpegUtil;
import com.example.base.utils.FileMD5Checksum;
import com.example.business.entity.SysConfig;
import com.example.business.entity.SysImg;
import com.example.business.service.SysConfigService;
import com.example.business.service.SysImgService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.business.entity.SysVideo;
import com.example.business.mapper.SysVideoMapper;
import com.example.business.service.SysVideoService;
import org.springframework.cache.annotation.*;

import java.io.File;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.CacheConfig;

/**
 * <p>
 * 视频表 服务实现类
 * </p>
 *
 * @author xiong
 * @since 2024-01-27
 */
@Service
@Transactional
@CacheConfig(cacheNames = "SysVideoServiceImpl")
public class SysVideoServiceImpl extends ServiceImpl<SysVideoMapper, SysVideo> implements SysVideoService {

    @Cacheable(cacheNames = "sysvideo",key = "#id")
    @Override
    public SysVideo getById(Serializable id){
        return super.getById(id);
    }

    @CacheEvict(cacheNames = "sysvideo", key = "#id")
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @CacheEvict(cacheNames = "sysvideo", key = "#sysvideo.id")
    @Override
    public boolean updateById(SysVideo sysvideo) {
        return super.updateById(sysvideo);
    }

    @CachePut(cacheNames = "sysvideo", key = "#sysvideo.id")
    public SysVideo saveSysVideo(SysVideo sysvideo){
        super.save(sysvideo);
        return sysvideo;
    }

    @CacheEvict(cacheNames = "sysvideo", key = "#sysvideo.id")
    public SysVideo updateSysVideoById(SysVideo sysvideo){
        super.updateById(sysvideo);
        return sysvideo;
    }

    @Cacheable(cacheNames = "sysvideo",key = "#md5")
    public SysVideo getSysVideoByMd5(String md5){
        LambdaQueryWrapper<SysVideo> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysVideo::getFilemd5,md5);
        return this.baseMapper.selectOne(lambdaQueryWrapper);
    }

    @CacheEvict(cacheNames = "sysvideo", key = "#id")
    @Override
    public void updatePlayerNumById(Serializable id) {
        SysVideo sysVideo=this.baseMapper.selectById(id);
        if(sysVideo!=null){
            if(sysVideo.getPalyernum()==null){
                sysVideo.setPalyernum(0);
            }
            sysVideo.setPalyernum(sysVideo.getId()+1);
            this.baseMapper.updateById(sysVideo);
        }
    }

    @Override
    public List<SysVideo> getListOrderById(Serializable id, Integer limit) {
        List<SysVideo> videos=this.baseMapper.getListOrderById(id,limit);
        return videos;
    }

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private SysImgService sysImgService;

    @Override
    public void scanVideo() throws Exception {
        SysConfig sysConfig=sysConfigService.getSysConfigByKey("path");
        File file=new File(sysConfig.getSysValue());
        File[] files=file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File f=files[i];
            if(f.isDirectory()){
                continue;
            }
            String fileType=getFileExtension(f);
            if(!"mp4".equals(fileType)){
                continue;
            }
            String md5=FileMD5Checksum.getMD5Checksum(f.getPath());
            SysVideo sysVideo=this.getSysVideoByMd5(md5);
            if(sysVideo!=null){
                continue;
            }
            String fileName=getFileNameWithoutExtension(f);

            System.out.println("md5值:"+md5);
            System.out.println(f.getName());
            Double time= FfmpegUtil.getVideoTime(f);

            String timePath=System.currentTimeMillis()+"_"+md5;
            String picPath=timePath+File.separator+md5+".jpeg";
            FfmpegUtil.getVideoPic(f,picPath);
            String base64Img=FfmpegUtil.convertImageToBase64(picPath);
            File pic=new File(picPath);
            pic.deleteOnExit();
            SysImg sysImg=new SysImg();
            sysImg.setBase64str(base64Img);
            sysImgService.saveSysImg(sysImg);

            File file1=new File(f.getParent()+File.separator+timePath);
            if(!file1.exists()){
                file1.mkdirs();
            }
            String m3u8=FfmpegUtil.mp4ToM3u8(f.getPath(),f.getParent()+File.separator+timePath);
            SysVideo video=new SysVideo();
            video.setCreatedate(new Date());
            video.setUpdatetime(new Date());
            video.setFilem3u8(timePath+"/"+m3u8);
            video.setFilepath(file1.getPath()+File.separator+m3u8);
            video.setFiletime(time);
            video.setFileimgid(sysImg.getId().toString());
            video.setFilemd5(md5);
            video.setFilename(fileName);
            video.setFiletype(fileType);
            video.setPalyernum(0);
            this.save(video);
        }
    }

    public String getFileExtension(File file) {
        if (file.exists() && !file.isDirectory()) {
            String fileName = file.getName();
            int dotIndex = fileName.lastIndexOf(".");
            if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
                return fileName.substring(dotIndex + 1);
            } else {
                return ""; // 文件没有后缀名
            }
        } else {
            return "文件不存在或是一个目录";
        }
    }

    private  String getFileNameWithoutExtension(File file) {
        String fileName = file.getName();
        int index = fileName.lastIndexOf('.');
        if (index != -1) {
            fileName = fileName.substring(0, index);
        }
        return fileName;
    }
}
